package cloud.redis;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


/**
 * @author cunfeng
 * @create 2021-05-06 10:33
 */
@Configuration
@EnableConfigurationProperties(MyRedisProperties.class)//开启属性注入,通过@autowired注入
@ConditionalOnClass(RedisClient.class)//判断这个类是否在classpath中存在
public class MyRedisAutoConfigulation {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MyRedisProperties prop;

    @Bean(name="jedisPool")
    public JedisPool jedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(prop.getMaxIdle());
        config.setMaxTotal(prop.getMaxActive());
        config.setMaxWaitMillis(prop.getMaxWait());
        int database = prop.getDatabase();
        String password = prop.getPassword();
        int timeout = prop.getTimeout();
        if(StringUtils.isNotBlank(password)){
            logger.info("初始化redis连接池完毕--------------");
            return new JedisPool(config, prop.getHost(), prop.getPort(),timeout,password,database);
        }else {
            logger.info("初始化redis连接池完毕--------------");
            return new JedisPool(config, prop.getHost(), prop.getPort(),timeout,null,database);
        }

    }

    @Bean
    @ConditionalOnMissingBean(RedisClient.class)//容器中如果没有RedisClient这个类,那么自动配置这个RedisClient
    public RedisClient redisClient(@Qualifier("jedisPool")JedisPool pool) {
        RedisClient redisClient = new RedisClient();
        redisClient.setJedisPool(pool);
        return redisClient;
    }

}